package org.quartz.impl.rmi;

import org.quartz.impl.rmi.entity.*;
import sun.security.krb5.Config;

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.math.BigDecimal;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Date;

import static org.quartz.impl.jdbcjobstore.Util.closeStatement;


/**
 * Created by guowei on 2018/1/14.
 */
public class DBAccessThread implements Runnable{
    private AbstractMessage am;
    private String sqlString;
    private ConfigMessage cm = null;
    public Object result;
    private MutexResource mutex;

    public DBAccessThread(AbstractMessage am, String sqlString, MutexResource mutex, ConfigMessage cm) {
        this.am = am;
        this.sqlString = sqlString;
        this.mutex = mutex;
        this.cm = cm;
    }

    @Override
    public void run() {
        PreparedStatement ps = null;
        try {
            ps = ServerJDBCDriverDelegate.getConn().prepareStatement(sqlString);
            switch(cm.getType()){
                case "SelectMisfiredTriggers":
                    SelectMisfiredTriggers smt = (SelectMisfiredTriggers)am;
                    ps.setBigDecimal(1, new BigDecimal(String.valueOf(smt.getTs())));
                    break;
                default:
                    result = "Not Support write-sql.";
            }
            result = ps.executeUpdate();
        } catch(SQLException e){
            e.printStackTrace();
            result =  new Integer(-1);
        } catch(Exception e){
            e.printStackTrace();
            result =  new Integer(-2);
        } finally {
            closeStatement(ps);
            mutex.releaseRLock();
        }
    }

    private static String getMethodName(String fildeName) throws Exception{
        byte[] items = fildeName.getBytes();
        items[0] = (byte) ((char) items[0] - 'a' + 'A');
        return new String(items);
    }
}
